﻿using Acme.BookStore.Books;
using Acme.BookStore.Bookss;
using Acme.BookStore.pay;
using Alipay.EasySDK.Factory;
using Alipay.EasySDK.Kernel;
using Alipay.EasySDK.Kernel.Util;
using Alipay.EasySDK.Payment.Page.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Acme.BookStore
{
    public class ALiPayAppService : ApplicationService, IALiPayAppService
    {
        private readonly IHttpContextAccessor _contextAccessor;

        public ALiPayAppService(IHttpContextAccessor contextAccessor)
        {
            _contextAccessor = contextAccessor;
        }
        [HttpGet]
        //直接测试用地址,记得改订单信息. https://localhost:44341/api/app/a-li-pay/pay?Subject=test1&outTradeNo=111111111112&totalAmount=500
        public async void Pay(PayDto dto)
        {
            #region 1. 设置参数（全局只需设置一次）
            var config = new Config()
            {
                Protocol = "https",
                GatewayHost = "openapi.alipaydev.com",//"openapi.alipay.com",沙箱
                SignType = "RSA2",
                AppId ="2021000118634882",
                //请填写您的应用私钥
                MerchantPrivateKey = "MIIEowIBAAKCAQEAjzGsJJ7a+gWC3Z73ccYHxxjfH/RpTNyKzvEdgqtVxUUuDliho863KKo17cSYWUCS2VjWx1/f7kzr+kMA2ipIkvxRumwrD9LYAmJw1PsHDzkNFK+uAhBSGqA6uGUQJ5eCimKBRMWIItd9NwgaFAW3XriKTT+eHuF59LNag5nLxgcSU+x5ZEFhwk3bejIuKcFN4jhqdCXueOAb//zdTwxJkqKGySxon2JP+eSM1IzHg1U0NHgTx1Hj7GLtaenGjqNXrFf17y8hroJZVSUlujq3QW6hA54rL1XKIx5CcvWKTA1l8SC0lddklBmUpwdl0pkQA1QtqC6CHJjFHCrl7gvXIwIDAQABAoIBAEEl71UF9UjVYxHjtl7MI1PBDBrkv1fZ60l1x+BghXhoHikmx/vYG9r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ySA6js42C/lQHricy4txzR+lsCprv/k4SwaxayhcFc2npOpIZC10rVRI9Tw33CH05c9QJg337rovswH6Y5smfRSnN74DC",
                //支付宝公钥
                AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjAQ/3euhRa5QZ3wTSfRfOmHvccbtEoy++b9sl7qWMMIFG4n1BWUgSxB1dTSCB047z1HaTxZ/wtzHyF7h3jCzhkHaqSqajdTfedn+FOpeIptUG+LebZBqtVeYjixi48Q3uysBLnTsXljkgDzkX5u1Ma2H/C/QzDLZT1GYnZ1k5+mL97qwViKYx3+TO8Ef+AU3LrTbuYMIaVdyqSYgxLVx/jxu+3OghAqHy9Bu1stux2OS8wXfsHYMMAzV7iERdgPFi9YF6x5SyVH39uv/M3COmgGW50And7T021ebI/7Zb8WGsqrSnXQSXAZz9TKsNsgOHPyI61giXTE7z5oV1DrrSQIDAQAB",
                //异步回调地址
                NotifyUrl = "https://localhost:44338/api/app/a-li-pay/notify-url",
            };
            Factory.SetOptions(config);
            #endregion
            try
            {
                // 2. 发起API调用（以创建当面付收款二维码为例）
                //TODO:实训标题和订单号及金额是从dto中取得
                AlipayTradePagePayResponse response = Factory.Payment.Page().Pay(dto.Subject, dto.outTradeNo, dto.totalAmount, "https://localhost:44338/api/app/a-li-pay/return-url");
                // 3. 处理响应或异常
                if (ResponseChecker.Success(response))
                {
                    //把返回的html直接变成网页显示
                    var data = Encoding.UTF8.GetBytes(response.Body);
                    _contextAccessor.HttpContext.Response.ContentType = "text/html";
                    await _contextAccessor.HttpContext.Response.Body.WriteAsync(data, 0, data.Length);
                }
                else
                {
                    Console.WriteLine("调用失败，原因：" + response.Body);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("调用遭遇异常，原因：" + ex.Message);
            }
            
        }
        [HttpGet]
        public string ReturnUrl(PayReturnDto dto)
        {
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters) == true)
            {
                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加商户网站唯一订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //if()先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update

                return "success";
            }
            return "";
        }
        [HttpGet]
        public string NotifyUrl(PayReturnDto dto)
        {
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters) == true)
            {
                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加商户网站唯一订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update
                //再循环返回库存
                return "success";
            }
            return "";
        }
    }
}

